package com.hemh.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.hemh.dao.OmsEmailMapper;
import com.hemh.entity.OmsEmail;
import com.hemh.entity.OmsEmailExample;
import com.hemh.utils.TimeUtils;
import com.hemh.utils.UUIDUtils;

@Service
public class EmailService {

	private static Logger logger = LoggerFactory.getLogger(EmailService.class);
	
	@Resource
	private OmsEmailMapper omsEmailMapper;
	
	/** 注入邮件工具类 */
    @Autowired
    private JavaMailSenderImpl mailSender ; 

	/**
	 * @author HeMingHui
	 * @since 2020-11-06
	 * @param emailSender
	 * @param emailRecevier
	 * @param emailTitle
	 * @param emailContent
	 * @return int: 0-失败, 1-成功
	 * @description 插入邮件记录(默认不删除, 未发送)
	 */
	public int insertEmailRecord(String emailSender, String emailRecevier, String emailTitle, String emailContent) {
		int result = 0;
		OmsEmail record = new OmsEmail();
		LocalDateTime nowTime = TimeUtils.getLocalDateTimeNow();
		String emailNumber = "EMAIL" 
				+ TimeUtils.localDateTimeFormat(nowTime, "yyyyMMdd")
				+ UUIDUtils.getUUIDUppercase();
		record.setEmailNumber(emailNumber);
		record.setEmailSender(emailSender);
		record.setEmailRecevier(emailRecevier);
		record.setEmailTitle(emailTitle);
		record.setEmailContent(emailContent);
		record.setEmailStatus("0");
		record.setDeleted("0");
		result = omsEmailMapper.insert(record);
		return result;

	}

	/**
	 * @author HeMingHui
	 * @since 2020-11-06
	 * @param OmsEmail
	 * @return int: 0-失败, 1-成功
	 * @description 更新邮件发送状态
	 */
	public int updateEmailStatus(OmsEmail email) {
		int result = 0;
		email.setEmailSendTime(TimeUtils.getLocalDateTimeNow());
		email.setEmailStatus("1");
		result = omsEmailMapper.updateByPrimaryKey(email);
		return result;
	}
	
	/**
	 * @author HeMingHui
	 * @since 2020-11-06
	 * @param emailStatus
	 * @return List<OmsEmail>
	 * @decription 根据邮件状态查询邮件列表
	 */
	public List<OmsEmail> getEMailListByStatus(String emailStatus){
		List<OmsEmail> emailList = new ArrayList<OmsEmail>();
		OmsEmailExample example = new OmsEmailExample();
		example.or().andEmailStatusEqualTo(emailStatus).andDeletedEqualTo("0");
		emailList = omsEmailMapper.selectByExample(example);		
		return emailList;
	}

    public void sendMimeMail(OmsEmail eMail){
        try {
            //true 表示支持复杂类型数据
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(),true);
            messageHelper.setFrom(eMail.getEmailSender());
            //messageHelper.setTo(mailDto.getTo().split(",")); //按照, 逗号进行分隔
            messageHelper.setTo(eMail.getEmailRecevier()); //按照, 逗号进行分隔
            messageHelper.setSubject(eMail.getEmailTitle());
            messageHelper.setText(eMail.getEmailContent());
            //抄送
           /* if(!StringUtils.isEmpty(mailDto.getCc())){
                messageHelper.setCc(mailDto.getCc());
            }*/
            //密送
           /* if(!StringUtils.isEmpty(mailDto.getBcc())){
                messageHelper.setBcc(mailDto.getBcc().split(",")); //密抄
            }*/
            //添加邮件附件
           /* if(mailDto.getMultipartFiles()!=null){
                for(MultipartFile multipartFile:mailDto.getMultipartFiles()){
                    messageHelper.addAttachment(Objects.requireNonNull(multipartFile.getOriginalFilename()),multipartFile);
                }
            }*/
            // 发送时间
            if(eMail.getEmailSendTime() == null){
            	eMail.setEmailSendTime(LocalDateTime.now());
                messageHelper.setSentDate(TimeUtils.localDateTimeConvertToDate(eMail.getEmailSendTime()) );
            }
            mailSender.send(messageHelper.getMimeMessage()); // 正式发送邮件
            eMail.setEmailStatus("1");
            /** 表内记录 */
            if(eMail.getId() != null) {
            	this.updateEmailStatus(eMail);
            }
            // 打日志
            logger.info("发送邮件成功：{}->{}",eMail.getEmailSender(), eMail.getEmailRecevier());

        } catch (MessagingException e) {
        	logger.error("-----》》》邮件发送失败 : " + e);
            throw new RuntimeException(e); //发送失败
        }
    }
    
 
}
